package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理，在controller中通过trycatch捕获到的异常统一送到此类的某个方法中进行处理，底层是基于代理(代理指定的controller(RestController.class, Controller.class)，将捕获到的异常送过来此类)
 */
//在此处指定拦截哪些controller的异常
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
//日志注解，log的由来
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法，指定SQLIntegrityConstraintViolationException.class类异常，一旦指定类捕获到该异常立即进入此方法
     * @return
     */
//    通过测试发现，一旦有重复用户名违反了数据库的唯一约束，将会报SQLIntegrityConstraintViolationException异常并且报错信息会有Duplicate entry字眼
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 异常处理方法，指定CustomException.class类异常，一旦指定类捕获到该异常立即进入此方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }

}
